<template>
  <div>
    <!-- 搜索框 -->

    <el-form :inline="true" :model="formUser" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="formUser.user" placeholder="搜索"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="userSelect" :plain="true" type="refresh"
          >搜索</el-button
        >

        <!-- 添加按钮 -->
        <el-button type="primary" @click="addUserForm = true"> 添加</el-button>
        <!-- 刷新页面按钮 -->
        <el-button type="primary" @click="refresh">刷新</el-button>
      </el-form-item>
    </el-form>

    <!-- 添加按钮模态框 -->
    <el-dialog title="新增供货商" :visible.sync="addUserForm">
      <el-form :model="userForm">
        <el-form-item label="供货商名称：" :label-width="formLabelWidth">
          <el-input
            v-model="userForm.userName"
            ref="userName"
            placeholder="请输入名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="供货商地址：" :label-width="formLabelWidth">
          <el-input
            v-model="userForm.address"
            ref="address"
            type="address"
            placeholder="请输入地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话：" :label-width="formLabelWidth">
          <el-input
            v-model="userForm.telephone"
            ref="telephone"
            type="telephone"
            placeholder="请输入联系电话"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注：" :label-width="formLabelWidth">
          <el-input
            v-model="userForm.remark"
            ref="remark"
            type="text"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserForm = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addUserFormClick()"
          :addConfirmLoading="false"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 编辑按钮 -->
    <!-- 编辑按钮模态框 -->
    <el-dialog title="编辑" :visible.sync="upUserForm">
      <el-form :model="updateUserForm">
        <el-form-item label="供货商名称：" :label-width="formLabelWidth">
          <el-input v-model="updateUserForm.userName" ref="userName"></el-input>
        </el-form-item>
        <el-form-item label="供货商地址：" :label-width="formLabelWidth">
          <el-input v-model="updateUserForm.address" ref="address"></el-input>
        </el-form-item>
        <el-form-item label="联系电话：" :label-width="formLabelWidth">
          <el-input
            v-model="updateUserForm.telephone"
            ref="telephone"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注：" :label-width="formLabelWidth">
          <el-input
            v-model="updateUserForm.remark"
            ref="remark"
            type="text"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="upUserForm = false">取 消</el-button>
        <el-button type="primary" @click="updateUserFormClick()"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 表格 -->
    <div style="box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)" class="one">
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="正在加载中请稍后......"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <el-table-column label="ID" width="180">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="供货商Id" prop="id"></el-table-column>
        <el-table-column label="供货商名称" width="180">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>姓名: {{ scope.row.userName }}</p>
              <p>创建时间：{{ scope.row.createdTime }}</p>
              <p>更新时间：{{ scope.row.updatedTime }}</p>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.userName }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="供货商地址" prop="address"></el-table-column>
        <el-table-column label="联系电话" prop="telephone"></el-table-column>
        <el-table-column label="是否启用">
          <template slot-scope="scope" align="center">
            <el-switch
              v-model="scope.row.isRecommendTwo"
              active-color="#52C4CD"
              @change="handelUpdate(scope.$index, scope.row)"
              inactive-color="#DCDFE6"
              :active-value="true"
              :inactive-value="false"
            ></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="备注" prop="remark"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="handleEdit(scope.$index, scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.$index, scope.row)"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="block">
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handlePageIndexChange"
        :current-page="pager.pageIndex"
        :page-size="pager.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pager.rowsTotal"
        background
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 添加模态框确定按钮加载中
      addConfirmLoading: false,
      // 分页
      tableData: [
        {
          id: "1",
          userName: "lhxtop",
          address: "123123",
          repassword: "123123",
          telephone: "1323555544",
          remark: "无",
        },
        {
          id: "2",
          userName: "qqq",
          address: "000000",
          repassword: "000000",
          telephone: "1542654556",
          remark: "无",
        },
      ],
      pager: {
        pageIndex: 1,
        pageSize: 10,
        rowTotal: 30,
      },

      // 添加按钮
      addUserForm: false,
      userForm: {
        id: "",
        userName: "",
        address: "",
        telephone: "",
        remark: "",
      },
      formLabelWidth: "120px",
      // 编辑按钮
      upUserForm: false,
      updateUserForm: {
        userName: "",
        address: "",
        telephone: "",
        remark: "",
        id: "",
        index: "",
      },
      // 查询用户
      formUser: {
        user: "",
      },
      // // 等待加载
      // loading: true,
    };
  },
  // provide / inject（注入依赖） 组合刷新页面
  inject: ["reload"],
  // 打开页面就开始用的方法
  mounted() {
    // 分页
    this.fecthData(this.pager);
  },

  methods: {
    // 编辑
    handleEdit(index, row) {
      console.log(index, row);
      //打开编辑框
      (this.upUserForm = true),
        (this.updateUserForm.userName = row.userName),
        (this.updateUserForm.address = row.address),
        (this.updateUserForm.telephone = row.telephone),
        (this.updateUserForm.remark = row.remark),
        (this.updateUserForm.id = row.id),
        (this.updateUserForm.index = index);
    },
    //删除
    handleDelete(index, row) {
      console.log(index, row);

      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 删除数据
          //删除接口deleteUser
          deleteUser(row.id)
            .then((data) => {
              console.log(data.code);
              if (data.code === 1000) {
                // 删除成功
                console.log(data);
                this.$message({
                  showClose: true,
                  message: "删除供货商成功",
                  type: "success",
                });
                // 使用splice删除tableData数组里面从下标为index开始的第一个数
                this.tableData.splice(index, 1);
              } else if (data.code === 1001) {
                this.$message({
                  showClose: true,
                  message: "删除供货商失败",
                  type: "error",
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 分页属性方法
    handlePageIndexChange(val) {
      // console.log(val);
      this.pager.pageIndex = val;
      this.fecthData(this.pager);
    },
    handlePageSizeChange(val) {
      // console.log(val);
      this.pager.pageSize = val;
      this.fecthData(this.pager);
    },
    // 添加按钮点击事件方法
    addUserFormClick() {
      var userName = this.$refs.userName.value.trim();
      var address = this.$refs.address.value.trim();
      var telephone = this.$refs.telephone.value.trim();
      var remark = this.$refs.remark.value.trim();
      // 添加加载中
      this.addConfirmLoading = true;
      // console.log(userName);
      // console.log(address);

      postAddUser(userName, address, telephone, remark)
        .then((res) => {
          // console.log(res);
          if (res.code === 1000) {
            // 添加加载中
            this.addConfirmLoading = false;
            // 关闭添加模态框
            this.addUserForm = false;
            // 用户添加成功后提示信息
            this.$message({
              showClose: true,
              message: "添加成功！",
              type: "success",
            });
            // 清空输入框
            this.userForm.userName = "";
            this.userForm.address = "";
            this.userForm.telephone = "";
            this.userForm.remark = "";
            // 刷新页面（// provide / inject 组合刷新页面）
            this.reload();
          } else if (res.code === 1001) {
            // 添加加载中
            this.addConfirmLoading = false;
            // 用户添加失败（用户名重复）后提示信息
            this.$message({
              showClose: true,
              message: "用户名重复，请重新尝试",
              type: "warning",
            });
          }
          console.log(res.msg);
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 编辑按钮点击后模态框的确认按钮点击事件
    updateUserFormClick() {
      var userName = this.updateUserForm.userName.trim();
      var address = this.updateUserForm.address.trim();
      var telephone = this.updateUserForm.telephone.trim();
      var remark = this.updateUserForm.remark.trim();
      if (userName !== "") {
        var data = { userName, address, telephone, remark };
        //更新编辑接口
        updateUser(this.updateUserForm.id, data).then((data) => {
          if (data.code === 1000) {
            // console.log(data);
            this.upUserForm = false;
            // console.log(this.updateUserForm.index);
            // 使用splice进行对数组操作
            this.tableData.splice(this.updateUserForm.index, 1, data.data);
            this.$message({
              showClose: true,
              message: "修改成功",
              type: "success",
            });
            console.log("修改成功");
          } else {
            this.$message({
              showClose: true,
              message: "修改失败",
              type: "error",
            });
            console.log("修改失败");
          }
        });
      } else {
        this.$message({
          showClose: true,
          message: "没有输入",
          type: "error",
        });
        console.log("内容为空！");
      }
    },
    // 供货商查询按钮
    userSelect() {
      // console.log(this.formUser.user);
      var searchContent = this.formUser.user;
      // console.log(searchContent);
      if (searchContent !== "") {
        // 搜索框存在类容
        postSelectUser(searchContent)
          .then((data) => {
            console.log(data);
            if (data.data.length != 0) {
              // console.log(3232);
              // 有查询到数据
              // console.log(data.data);

              this.tableData = data.data;
            } else {
              // 未查询到数据
              this.$message({
                message: "未搜索到数据哦",
                type: "warning",
              });
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        // 搜索框为空
        this.$message({
          message: "搜索框不能为空哦",
          type: "warning",
        });
      }
    },
    // 刷新按钮点击事件
    refresh() {
      this.reload();
    },
    handelUpdate(index, row) {
      console.log(index); // ：active-value得为true // ：inactive-value得为false
      let flag = row.isRecommendTwo; //保存点击之后v-modeld的值(true，false)

      row.isRecommendTwo = !row.isRecommendTwo; //保持switch点击前的状态

      this.$confirm("是否确认此操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (flag) {
            row.isRecommendTwo = true;
            // 逻辑处理
            this.$message.success("打开成功!");
          } else {
            row.isRecommendTwo = false;
            // 逻辑处理
            this.$message.success("关闭成功！");
          }
        })
        .catch(() => {
          this.$message.info("取消操作！");
        });
    },
  },
};
</script>

<style scoped>
.block {
  margin-top: 1rem;
}
</style>